<?php
namespace admin\service;

use admin\service\interfaces\IManagerService;
use common\service\CommonService;
use herosphp\bean\Beans;
use herosphp\core\Loader;
use herosphp\session\Session;
use herosphp\web\WebUtils;
use herosphp\string\StringUtils;
use herosphp\utils\ArrayUtils;

Loader::import('admin.service.interfaces.IManagerService');

/**
 * admin(Service)接口实现
 * @package admin\service
 * @author yangjian<yangjian102621@gmail.com>
 */
class ManagerService extends CommonService implements IManagerService {

    public function getItem($condition, $fields, $order)
    {
        $item = parent::getItem($condition, $fields, $order);
        if ( !empty($item['role_id']) ) {
            $model = Loader::model("ManagerRole");
            $role = $model->getItem($item['role_id']);
            $item['role_name'] = $role['name'];
            $item['permissions'] = StringUtils::jsonDecode($role['permissions']);
        }
        return $item;
    }

    public function getItems($conditions, $fields, $order, $limit, $group, $having)
    {
        $items = parent::getItems($conditions, $fields, $order, $limit, $group, $having);
        if ( !empty($items) ) {
            $ids = array();
            foreach ( $items as $val ) {
                $ids[] = $val['role_id'];
            }
            $model = Loader::model("ManagerRole");
            $roles = $model->getItems(array('id' => array('$in' => $ids)));
            $roles = ArrayUtils::changeArrayKey($roles, 'id');
            foreach ( $items as $key => $value ) {
                $items[$key]['role_name'] = $roles[$value['role_id']]['name'];
            }
        }

        return $items;
    }

    /**
     * 管理员登陆
     * @param $username
     * @param $password
     * @return mixed
     */
    public function login($username, $password)
    {
        $condition = array('username' => $username, 'password' => md5(md5($password)));
        $user = $this->getModelDao()->getItem($condition);
        if ( $user != false ) {
            //存储session
            Session::start();
            //初始化用户权限
            $roleService = Beans::get('admin.role.service');
            $role = $roleService->getItem($user['role_id']);
            $user['permissions'] = StringUtils::jsonDecode($role['permissions']);
            $_SESSION[self::MANAGER_SESSION_NAME] = $user;

            //更新最后登陆ip和登录时间
            $lastLoginTime = date('Y-m-d H:i:s');
            $lastLoginIp = WebUtils::getClientIP();
            $this->getModelDao()->update(
                array(
                    'last_login_time' => $lastLoginTime,
                    'last_login_ip' => $lastLoginIp,
                    'login_times' => $user['login_times'] + 1), $user['id']);

            //记录登陆日志
            $loginLogService = Beans::get('admin.loginLog.service');
            $data = array(
                'username' => $username,
                'name' => $user['name'],
                'ip' => $lastLoginIp,
                'addtime' => $lastLoginTime
            );
            $loginLogService->add($data);
        }
        return $user;
    }

    /**
     * 获取登陆的管理员
     * @return mixed
     */
    public function getLoginManager()
    {
        Session::start();
        if ( isset($_SESSION[self::MANAGER_SESSION_NAME]) ) {
            return $_SESSION[self::MANAGER_SESSION_NAME];
        } else {
            return false;
        }
    }

    public function setLoginManager($manager)
    {
        if ( !empty($manager) ) {
            Session::start();
            $_SESSION[self::MANAGER_SESSION_NAME] = $manager;
        }
    }

    /**
     * 判断当前用户是否登陆
     * @return bool
     */
    public function isLogin()
    {
        Session::start();
        return isset($_SESSION[self::MANAGER_SESSION_NAME]);
    }

    /**
     * 登出
     * @return mixed
     */
    public function logout()
    {
        Session::start();
        $_SESSION = null;
        session_destroy();
    }
}
